package fr.unice.CD.calendar;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.sun.org.apache.xerces.internal.dom.DocumentImpl;

public class SaveXML {
	public static void saveXML(String path, BeanEvent events)
			throws Exception {
		try {
			ArrayList<Event> lesEvent = events.getLesEvent();
			Element e = null;
			Node n = null;
			Document xmldoc = new DocumentImpl();
			// Root element.
			Element root = xmldoc.createElement("edt");
			for (Event leEvent : lesEvent) {
				e = xmldoc.createElementNS(null, "event");
				n = xmldoc.createElement("nom");
				n.setTextContent(leEvent.getNom());
				e.appendChild(n);
				n = xmldoc.createElement("dateDebut");
				n.setTextContent(leEvent.getDateDebut());
				e.appendChild(n);
				n = xmldoc.createElement("heureDebut");
				n.setTextContent(leEvent.getHeureDebut());
				e.appendChild(n);
				n = xmldoc.createElement("duree");
				n.setTextContent(leEvent.getDuree());
				e.appendChild(n);
				n = xmldoc.createElement("periodicite");
				n.setTextContent(leEvent.getPeriodicite());
				e.appendChild(n);
				n = xmldoc.createElement("lieu");
				n.setTextContent(leEvent.getLieu());
				e.appendChild(n);
				n = xmldoc.createElement("descriptif");
				n.setTextContent(leEvent.getDescriptif());
				e.appendChild(n);
				root.appendChild(e);
			}

			xmldoc.appendChild(root);

			// Create a transformer
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			xformer.setOutputProperty("encoding", "ISO-8859-1");
			xformer.setOutputProperty(OutputKeys.INDENT, "yes");
			// Write the DOM document to a file
			Source source = new DOMSource(xmldoc);
			Result result = new StreamResult(new File(path + "edt.xml"));
			xformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
}
